<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row>
        <el-col :span="8">
          <el-input v-model="queryInfo.query" clearable @clear="searchInfo">
            <el-button slot="append" icon="el-icon-search" @click="searchInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" class="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="usersList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="chageStatus(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserBtn(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <!-- 角色分配 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1,2,4,5]" :page-size="1"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 弹出框,添加用户用的 -->
    <el-dialog title="添加用户" :visible.sync="addVisible" width="40%" @close="addDialogClosed">
      <!-- 主要内容区域 -->

      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 需改用户信息弹出框 -->
    <el-dialog title="修改用户信息" :visible.sync="isDialogShow" width="30%" @close="clearClose">
      <!-- 表单区域 -->
      <el-form :model="editUserInfo" :rules="editUserRules" ref="editUserRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 表单按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配用户角色 -->
    <el-dialog @close="clearSetInfo" title="分配用户角色" :visible.sync="isDialogChecked" width="30%">
      <p>当前用户名：{{allotUserRoles.username}}</p>
      <p>当前角色：{{allotUserRoles.role_name}}</p>
      <el-select v-model="selectRolesId" placeholder="请选择">
        <el-option v-for="item in userRolesList" :key="item.id" :label="item.roleName" :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogChecked = false">取 消</el-button>
        <el-button type="primary" @click="setUserRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

export default {
  data: function () {
    // 自定义邮箱合验证规则
    var checkEmail = (rule, value, callback) => {
      var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (reg.test(value)) return callback()
      callback(new Error('你输入的邮箱不合法'))
    }
    // 自定义手机号验证规则
    var checkMobile = (rule, value, callback) => {
      var reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (reg.test(value)) return callback()
      callback(new Error('你输入的手机号不合法'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      usersList: [],
      searchVal: '',
      addVisible: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3到10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '请输入3到15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      isDialogShow: false, // 修改用户信息
      editUserInfo: {},
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      isDialogChecked: false,
      // 分配用户角色的信息
      allotUserRoles: {},
      // select分配用户列表的数据
      userRolesList: [],
      // 选中过后的值
      selectRolesId: ''
    }
  },
  created () {
    this.queryUserList()
  },
  methods: {
    async queryUserList () {
      const { data } = await this.$http.get('users', { params: this.queryInfo })
      if (data.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.total = data.data.total
      this.usersList = data.data.users
      console.log(this.usersList)
    },
    handleSizeChange (pagesize) {
      this.queryInfo.pagesize = pagesize
      this.queryUserList()
    },
    handleCurrentChange (pagenum) {
      this.queryInfo.pagenum = pagenum
      this.queryUserList()
    },
    searchInfo () {
      this.queryUserList()
    },
    addUser () {
      this.addVisible = true
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    addUsers () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 添加用户成功情况
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('用户添加失败')
        this.$message.success('用户添加成功')
        this.addVisible = false
        this.queryUserList()
      })
    },
    async chageStatus (status) {
      const { data: res } = await this.$http.put(`users/${status.id}/state/${status.mg_state}`)
      if (res.meta.status !== 200) {
        status.mg_state = !status.mg_state
      }
      // 状态修改成功
      this.$message.success('状态修改成功')
      this.queryUserList()
    },
    async editUserBtn (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败')
      // 查询用户成功的情况
      this.editUserInfo = res.data
      this.isDialogShow = true
    },
    clearClose () {
      // 重置表单的数据,不留下上一次操作的痕迹
      this.$refs.editUserRef.resetFields()
    },
    editUser () {
      this.$refs.editUserRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put('users/' + this.editUserInfo.id, {
          email: this.editUserInfo.email,
          mobile: this.editUserInfo.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('修改用户失败')
        this.$message.success('用户修改成功')
        this.editUserInfo = res
        // 更新表格用户数据
        this.queryUserList()
        // 关闭修改用户框
        this.isDialogShow = false
      })
    },
    async deleteUser (id) {
      const warningInfo = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(cancle => cancle)
      // 确认信息,打印confirm
      // 取消,打印cancel
      if (warningInfo === 'cancel') return this.$message.info('取消成功')
      // 这是确认删除的操作
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.queryUserList()
      this.$message.success('删除用户成功')
    },
    async setRoles (userInfo) {
      this.allotUserRoles = userInfo
      // 获取列表数据
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.userRolesList = res.data
      this.isDialogChecked = true
    },
    // 设置用户的权限，
    async setUserRoles () {
      const { data: res } = await this.$http.put(`users/${this.allotUserRoles.id}/role`, {
        rid: this.selectRolesId
      })
      if (res.meta.status !== 200) return this.$message.error('修改角色失败')
      this.queryUserList()
      this.isDialogChecked = false
    },
    // 关闭框之前，把框数据给清除一下痕迹
    clearSetInfo () {
      this.userRolesList = ''
      this.selectRolesId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.primary{
  margin-left: 30px;
}
.el-dialog{
  p{
    margin-bottom: 10px;
  }
}
</style>
